<template>
    <main>
        <div id="chat" class="chat">
            <div class="topInfo_button">
                <h3>公共聊天室</h3>
                <!-- <button class="greenButton" @click="设置()">设置</button> -->
                <el-button class="setButton" type="primary" plain @click="设置()">
                    <Setting style="height: 20px; width: 20px;" />
                    设置
                </el-button>
            </div>
            <div class="ChatMain">
                <el-scrollbar id="ChatTxt" class="ChatTxt" ref="scrollbar_1">

                    <div class="msg" v-show="false">
                        <div class="otherMsg">
                            <p class="userName">{{ UserName1 }}</p>
                            <div class="userImg_userMsg">
                                <img class="userImg" src="/userImg/user1.jpg" alt="" height="35px" width="35px"
                                    @click="更新消息();">
                                <span class="userMsg">你的浏览器ID:{{ compData.murmur }}</span>
                            </div>
                        </div>
                    </div>


                    <div class="msg" v-for="message in messages" :key="message.id">
                        <div class="" :class="message.uuid == compData.murmur ? 'myMsg' : ''">
                            <p class="userName">{{ message.name }}</p>
                            <p class="userID" v-show="true"><!-- {{ message.uuid }} -->
                                <!-- {{ img_random(message.uuid) }} -->
                                <!-- {{ message.img_url }} -->
                            </p>
                            <div class="userImg_userMsg">
                                <img class="userImg" :src="message.img_url" alt="" @click="到末尾()">
                                <div class="userMsg" :default="到末尾()">
                                    <div class="userMsgText">
                                        {{ message.text }}
                                    </div>
                                    <div class="msgButton">
                                        <div class="copyMsg" @click="copyMsg(message.text)">
                                            <el-tooltip content="复制" placement="bottom">
                                                <CopyDocument style="height: 18px;width: 18px;" />
                                            </el-tooltip>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </el-scrollbar>
                <div class="ChatInput">
                    <el-input v-model="UserMsg" style="width: 80%;max-width: 80%;"
                        :autosize="{ minRows: 1, maxRows: 5 }" type="textarea" placeholder="[Enter] 换行；[Ctrl+Enter] 发送"
                        @keydown="handleKeyDown" />

                    <el-button type="primary" @click="发送预处理()">发送</el-button>
                </div>
            </div>
        </div>
        <div class="chatSetting" :class="{ chatSetting_show: chatSetting }">
            <span class="Close_chatSetting" @click="设置(); 更新消息();">关闭</span>
            <ChatSetting ref="chatsetting" :UserId="UserId" />
        </div>
        <textarea name="" cols="30" rows="10" id="copyInput" class="hidden fixed_t_100"></textarea>
    </main>
</template>
<script setup>
import ChatSetting from "./ChildViews/ChatSetting.vue"
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
import { useStore } from 'vuex'
const store = useStore()

//=================0

//=================1
const warning_msg = (value) => {
    ElMessage({
        message: value,
        type: 'warning',
    })
}

const success_msg = (value) => {
    ElMessage({
        message: value,
        type: 'success',
    })
}
// 弹窗消息
//=================<
import Fingerprint2 from "fingerprintjs2"
import io from 'socket.io-client'
const compData = reactive({
    values: {},
    murmur: ""
})

const createFingerprint = () => {
    Fingerprint2.get((components) => {
        compData.values = components.map(component => component.value)
        compData.murmur = Fingerprint2.x64hash128(compData.values.join(""), 31).toUpperCase()
        UserId.value = compData.murmur
    })
}

if (window.requestIdleCallback) {
    requestIdleCallback(() => {
        createFingerprint()
    })
} else {
    setTimeout(() => {
        createFingerprint()
    }, 600)
}
//以上为 获取浏览器指纹
//=================>


//=================<
const chatsetting = ref("")
//此处为 获取子组件用户名称
//=================>


//=================<
const messages = ref([]);
const UserMsg = ref("");
const UserName1 = ref("");
const UserId = ref("");
let socket;
var i = -1;

function 发送预处理() {
    更新消息();
    UserName1.value == compData.murmur.slice(0, 5) ? warning_msg(`临时用户名${UserName1.value},可在[设置]中更改`) : null
    switch (UserName1.value) {
        case "":
        case null: warning_msg("用户名为空，[设置]中填写"); break;
        default:
            switch (UserMsg.value) {
                case "":
                case null: warning_msg("你没说话，我怎么发"); break;
                default:
                    发送新消息();
            }
    }
}
function img_random(value) {
    var img_random = value.match(/[0-9]/);
    var img_random_url = `userImg/user${img_random[0]}.jpg`
    return img_random_url;
}
onMounted(() => {
    socket = io("wss://mc00.top")

    socket.on('connect', () => {
        console.log('连接服务器成功');
    });
    socket.on('message', message => {
        message.msg.img_url = img_random(message.msg.uuid)
        messages.value.push(message.msg);
        // console.log(message.msg)
    });

    socket.on('old_message', message => {
        if (message.more > i) {
            message.msg.img_url = img_random(message.msg.uuid)
            messages.value.push(message.msg);
            i = message.more
        }
    });
    if (chatsetting.value.UserName) {
        UserName1.value = chatsetting.value.UserName
    }

})

function 更新消息() {
    // UserMsg.value = InputDiv.innerText;
    UserName1.value = chatsetting.value.UserName == "" ? compData.murmur.slice(0, 5) : chatsetting.value.UserName;
    UserId.value = compData.murmur;
}

function 发送新消息() {
    socket.emit('message', { text: UserMsg.value, uuid: UserId.value, name: UserName1.value });
    UserMsg.value = '';
    // InputDiv.innerText = '';
    // 检测行数();
}
const scrollbar_1 = ref(0)
function 到末尾() {
    setTimeout(() => {
        const ChatTxt = document.getElementById("ChatTxt");
        scrollbar_1.value.setScrollTop(ChatTxt.scrollHeight);
    }, 10);
}
const handleKeyDown = (event) => {
    if (event.ctrlKey && event.key === 'Enter') {
        发送预处理();
        event.preventDefault();
    }
};
//以上为处理聊天的代码
//=================>
const chatSetting = ref(false);
function 设置() {
    chatSetting.value = !chatSetting.value
}
function copyMsg(value) {
    if (value != '') {
        // navigator.clipboard.writeText(value);
        // success_msg("复制成功");
        // 需要https
        try {
            setTimeout(() => {
                const text = document.getElementById("copyInput")
                text.value = value
                text.select()
                document.execCommand('copy')
                success_msg("复制成功")
            }, 1);
        } catch (error) {
            warning_msg(`复制失败`)
        }
    }
}
</script>
<style scoped>
main {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.chat {
    height: calc(100vh - var(--headerHeight));
    width: 100%;
}

.topInfo_button {
    position: relative;
    max-width: 800px;
    margin: auto;
    display: flex;
    align-items: center;
    padding-left: 10px;
    padding-right: 10px;
    border: 1px solid #ccc;
    border-top: 0;
    border-bottom: 0;
    border-radius: 0;
}

button {
    border: 1px solid;
    height: 0.6cm;
    width: 1.2cm;
    border-radius: 5px;
    user-select: none;
}

.setButton {
    height: 25px;
    width: fit-content;
    padding: 0 10px;
}

h3 {
    width: 100%;
    text-align: center;
    height: 28px;
}

.无法选择 {
    user-select: none;
}

.greenButton {
    position: absolute;
    right: 0;
}

.ChatMain {
    height: calc(100% - 28px);
    max-width: 800px;
    border: 1px solid #ccc;
    border-top: 0;
    border-radius: 0 0 5px 5px;
    margin: auto;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
}

.ChatTxt {
    max-width: 800px;
    overflow: auto;
    width: 100%;
    position: relative;
}


.ChatInput {
    background-color: #ffffff;
    border-top: 1px solid #d6d6d6;
    padding-block: 3px;
    width: 100%;
    padding-left: 5px;
    padding-right: 5px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}

.InputDiv {
    width: 80%;
    min-width: 80%;
    /* height: 30px; */
    line-height: 30px;
    min-height: 30px;
    max-height: 150px;
    padding-left: 3px;
    padding-right: 3px;
    border: 1px solid;
    border-radius: 4px;
    overflow: auto;
}

.InputDiv:empty:before {
    content: attr(data-placeholder);
    color: #a8a8a8;
    display: block;
    cursor: text;
    line-height: 28px;
}

.ChatInput button {
    width: 18%;
    height: 30px;
    font-size: 17px;
}

.msg {
    width: 100%;
    padding-left: 5px;
    padding-right: 5px;
    padding-bottom: 10px;
}

.myMsg {
    display: flex;
    flex-direction: column;
    align-items: end;
}

.myMsg .userImg_userMsg {
    display: flex;
    flex-direction: row-reverse;
}

.myMsg .userMsg {
    background-color: rgb(144, 255, 144);
    border: 1px solid rgb(111, 179, 111);
    border-radius: 8px 0 8px 8px;
    margin-left: 40px;
}

.myMsg .userName {
    text-align: right;
    margin-right: 40px;
}

.otherMsg .userMsg {
    margin-right: 40px;
}

.userMsgText {
    padding: 5px 5px;
}

.userName {
    font-size: 11px;
    color: rgb(109, 109, 109);
    margin-left: 40px;
    display: inline;
}

.userID {
    font-size: 11px;
    color: rgb(255, 187, 86);
    display: inline;
}

.userImg_userMsg {
    display: flex;
    width: 100%;
}

.userImg {
    border-radius: 50%;
    margin-top: -12px;
    height: 35px;
    width: 35px;
}

.userMsg {
    display: block;
    margin-left: 5px;
    margin-right: 5px;
    padding: 5px;
    font-size: small;
    color: inherit;
    min-height: 28px;
    min-width: 0.5cm;
    max-width: calc(100% - 80px);
    height: fit-content;
    background-color: rgb(117, 255, 255);
    border-radius: 0 8px 8px 8px;
    border: 1px solid rgb(0, 226, 226);
    overflow-wrap: break-word;
    white-space: pre-wrap;
    position: relative;
}

.msgButton {
    border-top: 2px solid #d1d1d1;
    margin-top: 5px;
    padding-top: 5px;
    border-radius: 0;
}

.copyMsg {
    width: fit-content;
    padding: 5px 5px;
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
    color: #969696;
    display: flex;
    align-items: center;
}

.myMsg .copyMsg {
    right: 100%;
    left: inherit;
}

.copyMsg:hover {
    background-color: #00e4d9;
}

.chatSetting {
    position: fixed;
    right: 0;
    top: 0;
    height: 100vh;
    width: 100vw;
    background-color: rgba(233, 233, 233, 0.9);
    transition: 0.3s;
    transform: translateX(100%);
}

.chatSetting_show {
    transform: none;
}

.Close_chatSetting {
    position: absolute;
    bottom: 1cm;
    right: 50%;
    padding: 2px 10px;
    border-radius: 5px;
    transform: translateX(50%);
    background-color: #ffffff85;
    border: 1px solid;
    text-align: center;
    cursor: pointer;
    transition: 0.3s;
}

.Close_chatSetting:hover {
    border-color: #ff0000;
    color: #ff0000;
}
</style>